package com.han.verifycode.utils;


import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

public class FontsUtil {
    private static final Map<String, String> cnFontsMap = new HashMap<>();

    static {
        cnFontsMap.put("方正姚体", "/fonts/FZYTK.TTF");
        cnFontsMap.put("华文琥珀", "/fonts/STHUPO.TTF");
        cnFontsMap.put("华文彩云", "/fonts/STCAIYUN.TTF");
    }


    /**
     * 获取随即字体
     *
     * @param fontSize
     * @return
     */
    public static Font getRandomFont(int fontSize) {
        int allFonts = cnFontsMap.size();
        int index = RandomUtil.getRandom().nextInt(allFonts - 1);
        List<String> keys = cnFontsMap.keySet().stream().collect(Collectors.toList());
        String fname = keys.get(index);
        return getFont(fname, fontSize);
    }

    /**
     * 获取指定字体
     *
     * @param name
     * @param fontSize
     * @return
     */
    public static Font getFont(String name, int fontSize) {
        if (fontSize == 0) {//安全尺寸
            fontSize = 14;
        }
        //先在本地查找
        String path = cnFontsMap.get(name);
        if (path != null) {
            return loadFont(path, fontSize);
        }
        //加载本地字体
        return new Font(name, Font.ITALIC, fontSize);
    }

    public static Font loadFont(String fileName, float fontSize) {
        try (InputStream stream = FontsUtil.class.getResourceAsStream(fileName)) {
            Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, stream);
            if (fontSize != 0) {
                return dynamicFont.deriveFont(fontSize);
            }
            return dynamicFont;
        } catch (FontFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new java.awt.Font("宋体", Font.PLAIN, 14);
    }

    public static void main(String[] args) {
        Font f = getFont("方正书体", 20);
        System.out.println(f.getName());
    }

}
